# -*- coding: utf-8 -*-
# @Author  : pony.guan
# @Time    : 2021/10/18
# Description:

import os
import json
import socket
import requests
import zipfile

import pandas as pd


# def get_local_ip():
#     """
#     获取本地ipv4地址
#     """
#     try:
#         csock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
#         csock.connect(('8.8.8.8', 80))
#         addr, port = csock.getsockname()
#         csock.close()
#         return addr
#     except socket.error:
#         return "127.0.0.1"


def download_location_status(host):
    port = 19000
    if host.replace('.', '').isdigit():
        map_export = f'http://{host}:{port}/map/export'
    else:
        map_export = f'http://{host}/map/export'
    # host = '172.20.3.230'
    headers = {
        "Content-Type": "application/json"
    }
    r = requests.get(url=map_export, headers=headers)
    if r.status_code != 200:
        return {
            'code': 1001,
            'error': '请求错误'
        }
        # raise ValueError('请求错误')

    map_zip_file = 'ess_p/order_tool/map.zip'
    with open(map_zip_file, 'wb') as f:
        f.write(r.content)
    zf = zipfile.ZipFile(map_zip_file, "r")
    content = zf.read(zf.namelist()[0])

    with open('bb1.json' 'wb') as f:
        f.write(content)

    zf.close()

    location_msg = json.loads(content)['location']
    location_msg = [location for location in location_msg if location.get('locationTypeCode', '') == 'LT_SHELF_STORAGE']

    data = [
        {'location_code': location['code'],
         'container_code': location.get('containerCode', '')} for location in
        location_msg
    ]

    df = pd.DataFrame(data)

    df = df.sort_values('container_code', ascending=False)

    df.to_excel('location_status.xlsx', index=False)

    os.remove(map_zip_file)
    return {
        'code': 1000,
        'data': 'download success'
    }


# ip_domain = input('请输入ip或者域名:')

host = '172.20.3.230'
print(download_location_status(host))
